<!-- 课题就是写暂存，首先是获取后端的testdata，然后显示，之后是获取后端的分析结果，还有就是释放，此外一个返回，需要检查 -->

<template>
    <div class="ApplicationPage">
        <div class="RegionOfTreeIdUsed">
          <p class = "TreeName">决策模型名称：</p>
          <div class = "selectTreeName">
            <select id="test-dataset-select" v-model="selectedTreeToApplication" @change="onTreeApplicationChange">
              <option v-for="item in tableData" :key="item.num" :value="item.id">
                {{ item.id }}
              </option>
            </select> 
          </div>
        </div>

        <div class="RegionOfOpreation">
            <div class="OperationOfDataList">
                <el-table
                class="table-wrapper tableListForData"
                :data="testDataSetList"
                :header-cell-style="{'text-align':'center'}"
                :cell-style="{'text-align':'center'}"
                height=120
                size="mini"
                ref="table"
                border
                @row-click="handleRowClicked"
                highlight-current-row>
                    <el-table-column
                    prop="num"
                    label="编号"
                    width="150"
                    >
                    </el-table-column>

                    <el-table-column
                    prop="name"
                    label="文件名称"
                    >
                    </el-table-column>

                    <el-table-column label="操作" width="250" style="display: flex; justify-content: space-between;">
                        <template v-slot:default="scope">
                            <el-button 
                                type="danger" 
                                size="small" v-on:click.stop=deleteData(scope.row)>
                                    删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <div class="OperationOfButton">
                <el-upload
                class="uploadOperation" 
                action="url"
                accept=".csv"
                ref="upload"
                :file-list="fileList"
                :http-request="UploadData"
                :headers="headers"
                :auto-upload="true"
                :on-error="uploadFileError"
                :on-success="uploadFileSuccess"
                :on-exceed="exceedFile"
                :show-file-list="false"
                :limit="limitnum"
                multiple
                >
                <el-button class="buttonOfOperation">上传文件</el-button>
                </el-upload>
                <el-button @click="goBackToTreeDetail" class="buttonOfOperation">返回</el-button>
                <el-button @click="useTreeAnalyzeWithTreeIDAndDataID" class="buttonOfOperation">分析</el-button>
            </div>
        </div>
        <!-- <el-divider class="horizontalDivider" direction="horizontal" border-color="#cornflowerblue" width="5px"></el-divider> -->
        <div class="RegionOfDisplay">
            <div class="DisplayOfRawData">
                <div >
                    <p>待诊断数据预览</p>
                </div>
                <el-table 
                class="table-wrapper"
                border
                size="mini"
                height= "280"
                :header-cell-style="{'text-align':'center'}"
                :cell-style="{'text-align':'center'}"
                :data="RowDataToDisplay">
                    <el-table-column
                        fixed
                        v-for="column in columnsOfRawData"
                        :key="column.prop"
                        :prop="column.prop"
                        :label="column.label">
                    </el-table-column>
                </el-table>
            </div>
            
            <div class="DisplayOfResult">
                <div class="HeaderOfResultDisplay">
                    <p>分析结果</p>
                    <el-button class = "ButtonOfDownloadResult" @click="downloadResult">下载</el-button>
                </div>
                <el-table 
                class="table-wrapper"
                height= "280"
                border
                :header-cell-style="{'text-align':'center'}"
                :cell-style="{'text-align':'center'}"
                :data="ResultDataToDisplay">
                    <el-table-column
                    prop="result"
                    label="结果">
                    </el-table-column>
                </el-table>
            </div>
        </div>

    </div>
</template>

<script>
import Papa from 'papaparse';
import { ElUpload, ElButton, ElTable, ElTableColumn } from 'element-plus';
export default {
    components: {
    ElUpload,
    ElButton,
    ElTable,
    ElTableColumn,
  },
    data(){
        return{
            url:"http://localhost:8081/TreeApplication", 
            testDataSetList:[],
            selectedTreeToApplication:"",
            columnsOfRawData:[],
            columnsOfResultData:[],
            tableData:[],
            RowDataToDisplay:[],
            ResultDataToDisplay:[],
            treeIdofApplication:"",
            fileOfRowData:null,
            resultOfBlob:null,
            currentRow:null,
            mappingList:[]
        }
    },
    methods:{
        UploadData(param) {
            var fileObj = param.file;
            this.fileOfRowData = fileObj;
            var form = new FormData();
            form.append("file", fileObj);
            // this.displayResultOnTable(this.fileOfRowData);
            this.$axios.post('http://localhost/api/tree/uploadTestData', form,{
                headers: {        
                    'token': sessionStorage.getItem('token')
                }
                })
                .then((res) => {
                // 假设上传成功的逻辑处理
                if(res.data.data){
                    this.$message.success('文件上传成功');
                    console.log(res.data);
                    param.onSuccess(res);
                    this.fileOfRowData = null;
                }
                else{
                    this.$message.error('文件上传失败：'+res.data.msg);
                    console.log(res.data);
                    this.fileOfRowData = null;
                }
                })
                .catch((error) => {
                // 假设上传失败的逻辑处理
                param.onError(error);
                this.fileOfRowData = null;
                });
            },

            uploadFileError(err){
                console.log("error:"+err)
                this.$message.error("上传失败！")
            },
            uploadFileSuccess(response) {
                if(response.data.data){
                    this.GetDataList()
                }else{
                    this.$message.error(response.data.message+"未知错误");//文件上传错误提示
                }
            },


            exceedFile(){
                this.$message.error('只能上传'+this.limitnum+'个文件');
            },


            //获取文件列表
            async GetDataList() {
                this.$axios.get('http://localhost/api/tree/getTestDataList',{
                    headers: {        
                        'token': sessionStorage.getItem('token')
                        // token:"eyJhbGciOiJIUzI1NiJ9.eyJVc2VySWQiOiI3MDE3N2M5Yi1kNjVhLTQ0ZmUtODlkMS0wZDFlMzY1NmM0MDIiLCJleHAiOjE3MTIwMjkyMzd9.x7GvK27YZ_4FnJjrREjeFBo5e9MQesFzHAXzpn8uQuE"
                    }
                    })
                    .then((response) => {
                    console.log(response.data);
                    if (response.data.code == 200) {
                        this.testDataSetList = response.data.data.map((item,index) => ({
                            num: index + 1,
                            name: item.name
                        }));
                        this.mappingList = response.data.data.map((item) => ({
                            id: item.id
                        }));
                        console.log(this.testDataSetList)
                    } else {
                        console.error('获取文件列表失败', response.data.msg);
                        this.$message.error('获取文件列表失败：' + response.data.msg);
                    }
                    })
                    .catch((error) => {
                    console.error('获取文件列表失败', error);
                    this.$message.error('获取文件列表失败');
                    });
            },

            async deleteData(dataToDelete){
                const isSingle = !Array.isArray(dataToDelete);
                let dataNumsToDelete = isSingle ? [dataToDelete.num] : dataToDelete.map(row => row.num);
                let dataIdsToDelete = []
                let temp = this.mappingList
                dataIdsToDelete = dataNumsToDelete.map(function(index){
                    return temp[index-1].id
                })
                const params = new URLSearchParams()
                Array.from(dataIdsToDelete).forEach(item => {
                    params.append('ids', item);
                });
                this.$axios.delete(`http://localhost/api/tree/deleteTestData`,
                {
                    headers: {        
                        'token': sessionStorage.getItem('token')
                    },
                    data:dataIdsToDelete
                    })
                    .then((response) => {
                    console.log(response.data);
                    if (response.data.data) {
                        this.$message.success('文件删除成功');
                        this.GetDataList()
                    } else {
                        this.$message.error('删除失败：' + response.data.msg);
                    }
                    })
                    .catch((error) => {
                        console.error('删除文件失败', error);
                        this.$message.error('删除文件失败:' + error);
                    });
            },

            displayRowDataOnTable(rowdataFileToDisplay){
                if (rowdataFileToDisplay instanceof Blob) {
                    Papa.parse(rowdataFileToDisplay, {
                        complete: (result) => {
                            this.fillRowDataToDisplayWithCSVData(result.data);
                        },
                        header: false
                    });
                }
            },

            fillRowDataToDisplayWithCSVData(rowdataToDisplay) {
                console.log("rowdataToDisplay:" + rowdataToDisplay)
                if (rowdataToDisplay.length > 0) {
                    const headersOfTableData = rowdataToDisplay[0];
                    console.log("rowdataToDisplay:" + rowdataToDisplay[0])
                    this.columnsOfRawData = [{
                        prop: 'id',
                        label: '编号'
                    }, ...headersOfTableData.map(header => ({
                        prop: header,
                        label: header
                    }))];
                    console.log(this.columnsOfRawData);
                    const limitedData = rowdataToDisplay.slice(1, 501); // 取前500行数据
                    const tempOfRowData = limitedData.map((row, rowIndex) => {
                        let rowData = {
                            id: rowIndex + 1 // 添加编号，从1开始
                        };
                        headersOfTableData.forEach((header, index) => {
                            rowData[header] = row[index];
                        });
                        return rowData;
                    });
                    this.RowDataToDisplay = tempOfRowData
                    console.log("tempOfRowData" + tempOfRowData)
                }
            },

            useTreeAnalyzeWithTreeIDAndDataID(){
                if(this.currentRow != null)
                {
                    let idNeed = this.mappingList[this.currentRow.num - 1].id
                    console.log("this.treeIdofApplication"+this.treeIdofApplication)
                    const url = `http://localhost/api/tree/getFeedback?treeId=${this.treeIdofApplication}&dataId=${idNeed}`
                        this.$axios({
                                url: url,
                                method: 'GET',
                                responseType: 'blob', // 确保响应类型为blob，以便正确处理文件流
                                headers: {        
                                    'token': sessionStorage.getItem('token')
                                }
                            }).then((response)=>{
                            if(response.status == 200){
                                this.$message.success("分析成功!")
                                this.resultOfBlob = new Blob([response.data])
                                let fileOfBlob = new File([this.resultOfBlob], 'result.csv', {type: this.resultOfBlob.type})
                                this.displayResultOnTable(fileOfBlob)
                                fileOfBlob = null;
                            }
                            else{
                                this.$message.error("分析失败!")
                            }
                        }).catch((error) =>{
                            this.$message.error("分析失败:" + error)
                        })
                }
                else{
                    this.$message.error("请选择待诊断数据集！")
                }

            },

            displayResultOnTable(resultFileToDisplay){
                console.log(resultFileToDisplay instanceof Blob)
                if (resultFileToDisplay instanceof Blob) {
                    Papa.parse(resultFileToDisplay, {
                        complete: (result) => {
                            this.fillResultDataToDisplayWithCSVData(result.data);
                        },
                        header: false
                    });
                }
            },

            fillResultDataToDisplayWithCSVData(resultdataToDisplay) {
                console.log("start");
                if (resultdataToDisplay.length > 0) {
                    const lastColumnData = resultdataToDisplay.slice(1, 501).map(row => row[row.length - 1]); // 取前500行数据
                    this.ResultDataToDisplay = lastColumnData.map((item) => ({
                        result:item,
                    }));
                }
            },

            async GetTestData(idOfTestdata){
                let idNeed = this.mappingList[idOfTestdata-1].id
                const url = `http://localhost/api/tree/downloadTestData?id=${idNeed}`
                await this.$axios({
                    url: url,
                    method: 'GET',
                    responseType: 'blob', // 确保响应类型为blob，以便正确处理文件流
                    headers: {        
                        'token': sessionStorage.getItem('token')
                    }
                        }).then((response=>{
                        if(response.status == 200){
                            this.$message.success("数据拉取成功!")
                            // this.fileOfRowData = new Blob([response.data])
                            let TestDataBlob = new Blob([response.data])
                            this.resultOfBlob = TestDataBlob
                            this.fileOfRowData = new File([TestDataBlob], 'TestData.csv', {type: TestDataBlob.type})
                            this.displayRowDataOnTable(this.fileOfRowData)
                            this.fileOfRowData = null
                        }
                        else{
                            this.$message.error("数据拉取失败!")
                            console.log("response:" + response.status)
                        }
                })).catch((error) =>{
                    console.log("response:" + error)
                        this.$message.error("数据拉取失败:" + error)
                    })
            },

            handleRowClicked(row) {
                // 如果被点击的行已经被选中，则取消选中
                if (row == this.currentRow) {
                    this.$refs.table.setCurrentRow()
                    this.currentRow = null
                } else {
                // 否则选中该行
                    this.currentRow = row;
                    this.GetTestData(row.num)
                }
            },
            goBackToTreeDetail(){
                this.$router.push({
                path: '/TreeDetail',
                query: {
                    decisionTreeName: this.treeIdofApplication,
                    }
                })
            },
            downloadResult(){
                try {
                    let downloadUrl = window.URL.createObjectURL(this.resultOfBlob);
                    let link = document.createElement('a');
                    link.href = downloadUrl;
                    link.style.display = 'none';
                    let downloadingFileName = "result.csv"; // 默认文件名
                    link.setAttribute('download', downloadingFileName);
                    document.body.appendChild(link)
                    link.click(); // 触发下载
                    window.URL.revokeObjectURL(downloadUrl); // 释放掉blob对象
                    this.$message.success('文件下载成功');
                } catch (error) {
                    this.$message.error('文件下载失败：' + error);
                }
            },

            /**-----------------新增加选择决策树功能----------------------------------------------- */
            onTreeApplicationChange(){
                this.treeIdofApplication = this.selectedTreeToApplication
            },
            async fetchFileList() {
                this.$axios.get('http://localhost/api/tree/treeList', {
                headers: {
                    'token': sessionStorage.getItem('token')
                    // token:"eyJhbGciOiJIUzI1NiJ9.eyJVc2VySWQiOiI3MDE3N2M5Yi1kNjVhLTQ0ZmUtODlkMS0wZDFlMzY1NmM0MDIiLCJleHAiOjE3MTIwMjkyMzd9.x7GvK27YZ_4FnJjrREjeFBo5e9MQesFzHAXzpn8uQuE"
                }
                })
                .then(response => {
                console.log(response.data);
                if (response.data.code == 200) {
                    const fileList = response.data.data; // 获取数据数组
                    this.tableData = fileList.map((file,index) => ({
                    num:index+1,
                    id: file.treeName, 
                    dataSet: file.fileName,
                    }));
                    console.log(this.tableData); // 打印处理后的数据
                }
                })
                .catch(error => {
                console.error('获取决策模型列表失败', error);
                this.$message.error('获取决策模型列表失败:' + error);
                });
            },


    },
    mounted(){
        this.treeIdofApplication = this.$route.query.decisionTreeIdTobeUsed;
        this.tableData = [
            {num:1,id:3,dataSet:"sadkjhfg.csv"}
        ]
        this.selectedTreeToApplication = this.$route.query.decisionTreeIdTobeUsed;
        this.GetDataList();
        this.fetchFileList()
    }
}
</script>

<style scoped>

.ApplicationPage {
    display: flex;
    flex-direction: column;
    height: 82vh;
    background-color: #f5f5f5; /* 更加柔和的背景色 */
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0,0,0,0.1); /* 添加阴影效果 */
    padding: 10px; /* 添加内边距 */
}

.RegionOfTreeIdUsed {
    min-width: 98%;
    min-height: 4%;
    background-color: #2c3e50; /* 现代感的蓝色调 */
    color: white; /* 白色文字 */
    padding: 2px;
    border-radius: 8px; /* 圆角效果 */
    margin-bottom: 5px; /* 增加下边距 */
    box-shadow: 0 2px 4px rgba(0,0,0,0.1); /* 细微的阴影效果 */
    font-weight: bold;
}

.RegionOfOpreation{
    min-height: 15%;
}

.RegionOfOpreation, .RegionOfDisplay {
    display: flex;
    gap: 5px; 
}

.OperationOfDataList{
    min-width: 85%;
}

.OperationOfButton{
    display: flex;
    flex-direction:column;
    justify-content: center; 
    align-items: center; 
    margin-left: auto;
    margin-right: auto;

}

.RegionOfDisplay {
    flex-direction: row;
    margin-top: auto;
    max-height: 65vh; /* 你可以根据实际情况调整这个值 */
    overflow: hidden; /* 防止子组件溢出 */
    flex-direction:row;
    justify-content: center; 
    align-items: center; 
    border-radius: 8px; /* 圆角效果 */
    box-shadow: 0 2px 4px rgba(0,0,0,0.05); /* 细微的阴影效果 */
}

.DisplayOfRawData, .DisplayOfResult {
    max-height: 100%; /* 子容器继承父容器的最大高度 */
    overflow: hidden; /* 如果有溢出，隐藏不显示 */
}

.table-wrapper {
    max-height: calc(100% - 40px); /* 减去一些可能的内边距或标题栏高度 */
    overflow: auto; /* 显示滚动条 */
}

.DisplayOfRawData{
    min-width: 72%;
    min-height: 100%;
}
.DisplayOfResult{
    min-width: 22%;
    min-height: 100%;
}

.OperationOfDataList, .DisplayOfRawData, .DisplayOfResult {
    background-color: white; /* 背景色设置为白色增加对比 */
    border-radius: 8px; /* 圆角效果 */
    box-shadow: 0 2px 4px rgba(0,0,0,0.05); /* 细微的阴影效果 */
    padding: 15px; /* 内边距 */
    border: 1px solid #eaeaea;
}

.OperationOfButton .buttonOfOperation {
    background-color: #3498db; /* 按钮使用更加鲜艳的绿色 */
    color: white;
    border: none;
    padding: 10px 20px;
    font-size: 16px; /* 适当调整字体大小 */
    margin: 8px 0; /* 调整间距 */
    box-shadow: 0 2px 4px rgba(0,0,0,0.1); /* 按钮阴影 */
    transition: all 0.3s; /* 平滑过渡效果 */
}

.buttonOfOperation{
    justify-content: center; 
    align-items: center; 
    width: 90%; /* 宽度调整为90%，略小于容器宽度 */
}

[type="danger"] {
    background-color: #e74c3c; /* 柔和的红色 */
}

.OperationOfButton .buttonOfOperation:hover {
    background-color: #2980b9; /* 鼠标悬浮时的颜色变化 */
    box-shadow: 0 4px 8px rgba(0,0,0,0.15); /* 鼠标悬浮时的阴影加深 */
}

.horizontalDivider{
    background-color: #bdc3c7; /* 分隔线颜色调整 */
    width:100%;
    height:1px;
}

::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}

::-webkit-scrollbar-track {
    background: #f1f1f1;
}

::-webkit-scrollbar-thumb {
    background: #888;
}

::-webkit-scrollbar-thumb:hover {
    background: #555;
}

.table-wrapper {
    max-height: 38vh; /* 或者可以设置为具体的像素值，例如 max-height: 300px; */
    overflow-y: auto; /* 允许在需要时显示滚动条 */
    border-radius: 4px; /* 添加圆角 */
    box-shadow: 0 2px 4px rgba(0,0,0,0.1); /* 添加阴影效果 */
}

.OperationOfButton .buttonOfOperation {
    padding: 12px 24px; /* 调整按钮的内边距 */
    font-size: 15px; /* 调整字体大小 */
}

.RegionOfTreeIdUsed {
    padding: 5px; /* 调整内边距 */
    font-size: 16px; /* 调整字体大小 */
    background-color: #2980b9; /* 调整背景颜色 */
}
.TreeName {
  margin-right: 10px; /* 在文字和选择框之间添加一些间隔 */
}

.selectTreeName {
  display: inline-block; /* 使选择框与文字在同一行显示 */
}

.HeaderOfResultDisplay {
    display: flex;
    justify-content: center; /* 确保内容水平居中 */
    align-items: center; /* 垂直居中 */
    width: 100%; /* 容器宽度设为100% */
    position: relative; 
}

.ButtonOfDownloadResult {
    position: absolute; /* 绝对定位 */
    right: 0; /* 右对齐 */
    margin-right: 16px; /* 与容器右侧保持一定的距离 */
    background-color: #3498db; /* 按钮背景颜色 */
    color: white; /* 字体颜色 */
    border: none; /* 无边框 */
    padding: 8px 16px; /* 内边距 */
    border-radius: 4px; /* 圆角边框 */
    cursor: pointer; /* 鼠标悬停时显示手形光标 */
    box-shadow: 0 2px 4px rgba(0,0,0,0.2); /* 阴影效果 */
    transition: background-color 0.3s, box-shadow 0.3s; /* 过渡动画 */
}

.ButtonOfDownloadResult:hover {
    background-color: #2980b9; /* 鼠标悬停时的背景颜色 */
    box-shadow: 0 4px 8px rgba(0,0,0,0.3); /* 鼠标悬停时的阴影效果加深 */
}

.buttonOfOperation {
    background-color: #3498db; /* 按钮背景颜色，淡蓝色，与下载按钮一致 */
    color: white; /* 字体颜色，白色以确保可读性 */
    border: none; /* 无边框，保持简洁 */
    padding: 10px 20px; /* 内边距，确保足够的点击区域 */
    font-size: 14px; /* 字体大小，确保文字清晰可读 */
    margin: 8px 0; /* 上下间距，保持元素之间的空间 */
    border-radius: 4px; /* 圆角，使按钮看起来更友好 */
    cursor: pointer; /* 当鼠标悬停时显示手形光标，明确这是一个可点击的元素 */
    box-shadow: 0 2px 4px rgba(0,0,0,0.2); /* 阴影，增加层次感 */
    transition: background-color 0.3s, box-shadow 0.3s; /* 过渡效果，增加用户交互体验 */
}

.buttonOfOperation:hover {
    background-color: #2980b9; /* 鼠标悬停时的背景颜色，深一点的蓝色 */
    box-shadow: 0 4px 8px rgba(0,0,0,0.3); /* 鼠标悬停时阴影加深，增加视觉反馈 */
}
</style>